package com.zbkj.service.service.standard.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorBigInt;
import com.googlecode.aviator.runtime.type.AviatorJavaType;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.zbkj.common.model.standard.PeFormula;
import com.zbkj.service.dao.standard.PeFormulaMapper;
import com.zbkj.service.service.standard.IPeFormulaService;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 公式表 服务实现类
 * </p>
 *
 * @author 
 * @since 2025-08-08
 */
@Service
public class PeFormulaServiceImpl extends ServiceImpl<PeFormulaMapper, PeFormula> implements IPeFormulaService {

    @Override
    public double calculateFormula(Long standardId, String projectId) {
        List<PeFormula> list = this.lambdaQuery().eq(PeFormula::getStandardId, standardId)
                .orderByDesc(PeFormula::getSort)
                .list();
        Map<String, Double> variableMap = new HashMap<>();
        for (PeFormula peFormula : list) {
            String expression = peFormula.getExpression();
            // 这里可以使用一个表达式计算库来计算表达式
        }
        return 0.0; // 返回计算结果
    }


    public static void main(String[] args) {
        AviatorEvaluator.addFunction(new MinFunction());
        String expression = "listsum(a,b)";
        Expression compiledExp = AviatorEvaluator.compile(expression, true);
        Map<String, Object> env = new HashMap<>();
        env.put("a0", 100.3);
        env.put("b0", 45);
        env.put("a1", 100.3);
        env.put("b1", 45);
        env.put("c", 200);
        Double result = (Double) compiledExp.execute(env);
        System.out.println(result);
    }

    static class MinFunction extends AbstractFunction {
        @Override public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
            String name1 = ((AviatorJavaType) arg1).getName();
            String name2 = ((AviatorJavaType) arg2).getName();
            Set<String> strings = env.keySet();
            Integer count = 0;
            for (String string : strings) {
                if(string.startsWith(name1)){
                    count += 1;
                }
            }
            double sum = 0;
            for (Integer i = 0; i < count; i++) {
                Number o1 = (Number)env.get(name1 + i);
                Number o2 = (Number)env.get(name2 + i);
                System.out.println(o1 + " * " + o2);
                sum += o1.doubleValue() * o2.doubleValue();
                System.out.println(sum  );
            }
            return new AviatorBigInt(sum);
        }

        public String getName() {
            return "listsum";
        }
    }

}
